<?php

namespace app\common\model;

use app\index\controller;
use think\Model;

class UserListModel extends Model
{
    //
    public
        $table = 'cms_blog_user',
        $pk = 'id';

    public function getList(){
        try {
            $sql = "SELECT id,name,account,phone,register_time FROM {$this->table} ORDER BY id desc";
            $res = $this->query($sql);
            $data = [];
            foreach ($res as $v) {
                $data[] = [
                    'id' => $v['id'],
                    'name' => $v['name'],
                    'account' => $v['account'],
                    'phone' => $v['phone'],
                    'register_time' => !empty($v['register_time']) ? date('Y-m-d H:i:s',$v['register_time']) : '',
                ];
            }
            return ["code" => 0, "msg" => "", "count" => 1000, "data" => $data];
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function updateData($param)
    {
        try {
            $decrypt = new CommonModel();
            if(empty($param['name'])){
                return ['code' => 0, 'message' => '昵称不能为空'];
            }
            if(empty($param['phone'])){
                return ['code' => 0, 'message' => '手机不能为空'];
            }
            if(empty($param['password'])){
                return ['code' => 0, 'message' => '密码不能为空'];
            }
            $dataInfo = $this->userQuery($param);
            if($dataInfo['code'] == 0){
                return $dataInfo;
            }
            $data = [
                'name' => $param['name'],
                'account' => uniqid(),
                'phone' => $param['phone'],
                'email' => !empty($param['email']) ? $param['email'] : '',
                'password' => $decrypt->thinkEncrypt($param['password']),
                'register_time'=> time()
            ];

            $sql = $this->save($data);
            if ($sql) {
                return ['code' => 200, 'message' => '添加成功'];
            } else {
                return ['code' => 0, 'message' => '添加失败'];
            }
        } catch (\Exception $e) {
            echo $e->getMessage() . '.........' . $e->getLine();
        }
    }

    //查询账号是否存在
    public function userQuery($param){
        $sqlInfo = $this->where('name',$param['name'])->find();
        if ($sqlInfo){
            return ['code' => 0, 'message' => '昵称已存在'];
        }
        $sqlData = $this->where('phone',$param['phone'])->find();
        if ($sqlData){
            return['code' => 0, 'message' => '该手机号已经注册'];
        }
        $sqlData = $this->where('email',$param['email'])->find();
        if ($sqlData){
            return['code' => 0, 'message' => '该邮箱已经注册'];
        }
        return ['code' => 1];
    }




}
